package servlet;

import model.User;
import service.ShareService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 记录分享行为的Servlet
 */
@WebServlet(name = "share_record", urlPatterns = "/share_record")
public class ShareRecordServlet extends HttpServlet {

    private ShareService shareService = new ShareService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应格式
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        // 获取参数
        String goodsIdStr = request.getParameter("goodsid");
        String shareType = request.getParameter("type");
        
        if (goodsIdStr == null || shareType == null) {
            out.print("{\"success\":false,\"message\":\"参数错误\"}");
            return;
        }
        
        try {
            int goodsId = Integer.parseInt(goodsIdStr);
            String clientIp = request.getRemoteAddr();
            
            // 从会话中获取用户信息
            User user = (User) request.getSession().getAttribute("user");
            Integer userId = user != null ? user.getId() : null;
            
            // 记录分享行为
            boolean success = shareService.recordShare(userId, goodsId, shareType, clientIp);
            
            if (success) {
                out.print("{\"success\":true,\"message\":\"分享记录成功\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"分享记录失败\"}");
            }
        } catch (NumberFormatException e) {
            out.print("{\"success\":false,\"message\":\"商品ID格式错误\"}");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
} 